package com.example.coolweather.activity;


import java.util.ArrayList;
import java.util.List;

import com.example.coolweather.db.CoolWeatherDB;
import com.example.coolweather.model.City;
import com.example.coolweather.model.County;
import com.example.coolweather.model.Province;
import com.example.coolweather.util.HttpCallbackListener;
import com.example.coolweather.util.HttpUtil;
import com.example.coolweather.util.Utility;

//import android.R;
import com.example.coolweather.*; 

//这里应该导入的是本工程的R文件，如果导入安卓的R文件，会导致找不到xml文件的数据
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ChooseAreaActivity extends Activity{

	public static final int LEVEL_PROVINCE = 0;
	public static final int LEVEL_CITY = 1;
	public static final int LEVEL_COUNTY =2;
	
	private ProgressDialog progressDialog;
	private TextView titleText;
	private ListView listView;
	private ArrayAdapter<String> adapter;
	private CoolWeatherDB coolWeatherDB;
	private List<String> dataList = new ArrayList<String>();
	
	private List<Province> provinceList;
	private List<City> cityList;
	private List<County> countyList;
	
	private Province selectedProvince;
	private City selectedCity;
	private County selectedCounty;
	
	private int currentLevel;
	private final static String TAG = "ChooseAreaActivity";
	
	/*
	 * 判断是否从WeatherActivity跳转过来
	 * */
	private Boolean isFromWeatherActivity;
	
	@Override
	protected void onCreate(Bundle saveInstanceState) {
		super.onCreate(saveInstanceState);
		isFromWeatherActivity = getIntent().getBooleanExtra("from_weather_activity", false);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		if (prefs.getBoolean("city_selected", false) && !isFromWeatherActivity) {
			//已经选择了城市且不是从WeatherActivity转过来的，才会直接跳到WeatherActivity
			Boolean iBoolean =prefs.getBoolean("city_selected", false);
			Boolean jBoolean =prefs.getBoolean("city_selected", true);
			String iString = Boolean.toString(iBoolean);
			String jString = Boolean.toString(jBoolean);
			Log.d("WeatherActivity", iString);
			Log.d("WeatherActivity", jString);
			Intent intent = new Intent(this,WeatherActivity.class);
			startActivity(intent);
			finish();
		}
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.choose_area);
		listView = (ListView) findViewById(R.id.list_view);
		titleText = (TextView) findViewById(R.id.title_text);
		adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, dataList);
		listView.setAdapter(adapter);
		coolWeatherDB = CoolWeatherDB.getInstance(this);
		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int index, long arg3) {
				// TODO Auto-generated method stub
				if (currentLevel == LEVEL_PROVINCE) {
					selectedProvince = provinceList.get(index);
					queryCities();
				} else if (currentLevel == LEVEL_CITY) {
					selectedCity = cityList.get(index);
					queryCounties();
				} else if (currentLevel == LEVEL_COUNTY) {
					selectedCounty = countyList.get(index);
					Intent intent =new Intent(ChooseAreaActivity.this,WeatherActivity.class);
					intent.putExtra("county_code", selectedCounty.getCountyCode());
					startActivity(intent);
					finish();
				}
			}
		});
		queryProvinces();  //加载省级数据
	}
	
	//查询省级数据，优先从数据库查询，如果没有再从服务器查询
	private void queryProvinces(){
		provinceList = coolWeatherDB.loadProvinces();
		Log.d(TAG, "queryProvinces");
		if (provinceList.size() > 0) {
			dataList.clear();
			Log.d(TAG, "进入provinceList");
			for (Province province : provinceList) {
				dataList.add(province.getProvinceName());
			}
			closeProgressDialog();
			adapter.notifyDataSetChanged();
			listView.setSelection(0);
			titleText.setText("中国");
			currentLevel = LEVEL_PROVINCE;
		} else {
			queryFromServer(null, "province");  //从服务器读取数据
		}
	}
	
	//查询省内所有城市
	private void queryCities() {
		Log.d(TAG, "进入cityList1");
		cityList = coolWeatherDB.loadCities(selectedProvince.getId());
		Log.d(TAG, "进入cityList");
		if (cityList.size() > 0) {
			dataList.clear();
			for (City city : cityList) {
				dataList.add(city.getCityName());
			}
			closeProgressDialog();
			adapter.notifyDataSetChanged();
			listView.setSelection(0);
			titleText.setText(selectedProvince.getProvinceName());
			currentLevel = LEVEL_CITY;
		} else {
			queryFromServer(selectedProvince.getProvinceCode(), "city");  //从服务器读取数据
		}
	}
	
	//查询市内所有城市
		private void queryCounties() {
			Log.d(TAG, "进入county1");
			countyList = coolWeatherDB.loadCounties(selectedCity.getId());
			Log.d(TAG, "进入county2");
			if (countyList.size() > 0) {
				dataList.clear();
				for (County county : countyList) {
					dataList.add(county.getCountyName());
				}
				closeProgressDialog();
				adapter.notifyDataSetChanged();
				listView.setSelection(0);
				titleText.setText(selectedCity.getCityName());
				currentLevel = LEVEL_COUNTY;
			} else {
				queryFromServer(selectedCity.getCityCode(), "county");  //从服务器读取数据
			}
		}
		
		//根据传入的代号和类型从服务器上查询省市县数据
		private void queryFromServer(final String code, final String type) {
			String address;
			if (!TextUtils.isEmpty(code)) {
				address = "http://www.weather.com.cn/data/list3/city" + code + ".xml";
				Log.d(TAG, address);
			} else {
				address = "http://www.weather.com.cn/data/list3/city.xml";
				Log.d(TAG, address);
			}
			showProgressDialog();
			Log.d(TAG, "showProgressDialog");
			HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
				@Override
				public void onFinish(String response) {
					// TODO Auto-generated method stub
					Log.d(TAG, "进入sendHttpRequest的onFinish");
					
					boolean result = false;
					if ("province".equals(type)) {
						result = Utility.handleProvincesResponse(coolWeatherDB, response);
						Log.d(TAG, "type is "+type);
					} else if ("city".equals(type)) {
						Log.d(TAG, "type is "+type);
						result = Utility.handleCitiesResponse(coolWeatherDB, response, selectedProvince.getId());
					} else if ("county".equals(type)) {
						Log.d(TAG, "type is "+type);
						result = Utility.handleCountiesResponse(coolWeatherDB, response, selectedCity.getId());
					}
					if (result) {
						// 通过runOnUiThread()方法回到主线程处理逻辑
						runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								Log.d(TAG, "进入run（）"+type);
								
								if ("province".equals(type)) {
									queryProvinces();
								} else if ("city".equals(type)) {
									queryCities();
								} else if ("county".equals(type)) {
									queryCounties();
								}					
							}
						});
					}
				}
				
				@Override
				public void onError(Exception e) {
					// TODO Auto-generated method stub
					//通过runOnUiThread()方法回到主线程处理逻辑
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							closeProgressDialog();
							Toast.makeText(ChooseAreaActivity.this, "加载失败", Toast.LENGTH_LONG).show();
						}
					});
				}
			});
		}

		//显示进度对话框
		private void showProgressDialog() {
			// TODO Auto-generated method stub
			if (progressDialog == null) {
				progressDialog = new ProgressDialog(this);
				progressDialog.setMessage("正在加载...");
				progressDialog.setCanceledOnTouchOutside(false);
			}
			progressDialog.show();
		}
		
		//关闭进度对话框
		private void closeProgressDialog() {
			if (progressDialog != null) {
				progressDialog.dismiss();
			}
		}
		
		/*
		 * 捕获Back键，根据当前级别判断返回的是市列表，省列表，或者直接退出
		 * */
		@Override
		public void onBackPressed() {
			if (currentLevel == LEVEL_COUNTY) {
				queryCities();
			} else if (currentLevel == LEVEL_CITY) {
				queryProvinces();
				} else {
					if (isFromWeatherActivity) {
						Intent intent = new Intent (this,WeatherActivity.class);
						startActivity(intent);
					}
					finish();
			}
		}
}

